if (typeof gonu == 'undefined') { gonu = {}; }
if (typeof gonu.play == 'undefined') { gonu.play = {}; }

gonu.play.viewCharm = {
		
	_oBoardCtx : null,
	stage : null,
	layer : null,
	_playRocks : [],
	_moveRocks : [],
	_xRocks : [],
	
	x : 25,
	y : 25,
	shortDistance : 42,
	rockRadius : 20,
	marginX : 0,
	marginY : 0,
	
	_chnlNumber : null,
	_order : null,
	_name : null,
	_moveRock : null,
	_moveCircles : [],
	_isClickRock : false, 
	_noticeElement : null,
	_rockAudio : null,
	
	_playStatus : null,
	
	init : function (playStatus, chnlNumber, order, name){
		/*
		this._rockAudio = new Audio('/resources/rock.wav');
		this._rockAudio.addEventListener("ended", function () {
			this.currentTime=0;
	        }, false);
	    */
		$Fn(this._goHome, this).attach($Element("giveUpButton"), "click");
		
		var size = $Document().scrollSize();
		this._noticeElement = $Element("notice");
		this.marginX = Math.floor((size.width - this.shortDistance*7)/4);
	    if (this.marginX<1) {
	    	this.marginX = 1;
	    }
	    this.marginY = Math.floor((size.height - this.shortDistance*7)/4);
	    if (this.marginY<1) {
	    	this.marginY = 1;
	    }
	    
	    this.x = this.x*1 + this.marginX;
	    this.y = this.y*1 + this.marginY;
	    
		this._order = order;
		this._name = name;
		this._chnlNumber = chnlNumber;
		this._drawBoard();
		
		this._playCheck();
	},
	_canvasInit : function () {
		this._deletePlayRocks();
		this._deleteChoiceMoveRocks();
		this._deleteMoveCircles();
		this._deleteXRocks();
		this._drawPlayRocks(this._playStatus);
		this._drawChoiceMoveRocks(this._playStatus);
		this._drawXRocks(this._playStatus);
		this.layer.draw();
	},
	_goHome : function () {
		var checkUrl = "/gonu/play/api/withdraw.json?chnlNumber=" + this._chnlNumber;
		var ajax = $Ajax(checkUrl, {
			type : 'xhr',
	        method : 'get', 
	        async : false,
	        onload : function(res) {
	            if(!!res){
					var response = res.json();
					var message = response.message;
					if(message == "ok"){
						$("charmForm").action = "/gonu/home.gonu";
						$("charmForm").submit();
					} 
				} else {
					location.href="/gonu/home.gonu";
				}
	        }
	    });
		
		ajax.request();
		
	},
	_drawBoard : function () {
		var size = $Document().scrollSize();
	    this.stage = new Kinetic.Stage({
	    	container: 'container',
	        width: (size.width> this.shortDistance*7) ? size.width:this.shortDistance*7,
	        height: (size.height> this.shortDistance*7) ? size.height:this.shortDistance*7
	      });
			
		this.layer = new Kinetic.Layer();
		
		var outRect = new Kinetic.Rect({
	        x: this.x,
	        y: this.y,
	        width: this.shortDistance*6,
	        height:this.shortDistance*6,
	        stroke: 'black',
	        strokeWidth: 1
	      });
		
		
		var middleRect = new Kinetic.Rect({
	        x: this.x+this.shortDistance,
	        y: this.y+this.shortDistance,
	        width: this.shortDistance*4,
	        height:this.shortDistance*4,
	        stroke: 'black',
	        strokeWidth: 1
	      });
		
		var inRect = new Kinetic.Rect({
	        x: this.x+this.shortDistance*2,
	        y: this.y+this.shortDistance*2,
	        width: this.shortDistance*2,
	        height:this.shortDistance*2,
	        stroke: 'black',
	        strokeWidth: 1
	      });
		
		
		var lineFirst = new Kinetic.Line({
	        points: [this.x, this.y, this.x+this.shortDistance*2, this.y+this.shortDistance*2],
	        stroke: 'black',
	        strokeWidth: 1
	      });
		var lineSecond = new Kinetic.Line({
	        points: [this.x+this.shortDistance*3, this.y, this.x+this.shortDistance*3, this.y+this.shortDistance*2],
	        stroke: 'black',
	        strokeWidth: 1
	      });
		var lineThird = new Kinetic.Line({
	        points: [this.x+this.shortDistance*6, this.y, this.x+this.shortDistance*4, this.y+this.shortDistance*2],
	        stroke: 'black',
	        strokeWidth: 1
	      });
		var lineFourth = new Kinetic.Line({
	        points: [this.x, this.y+this.shortDistance*3, this.x+this.shortDistance*2, this.y+this.shortDistance*3],
	        stroke: 'black',
	        strokeWidth: 1
	      });
		var lineFifth= new Kinetic.Line({
	        points: [this.x+this.shortDistance*4, this.y+this.shortDistance*3, this.x+this.shortDistance*6, this.y+this.shortDistance*3],
	        stroke: 'black',
	        strokeWidth: 1
	      });
		var lineSixth = new Kinetic.Line({
	        points: [this.x, this.y+this.shortDistance*6, this.x+this.shortDistance*2, this.y+this.shortDistance*4],
	        stroke: 'black',
	        strokeWidth: 1
	      });
		var lineSeventh = new Kinetic.Line({
	        points: [this.x+this.shortDistance*3, this.y+this.shortDistance*6, this.x+this.shortDistance*3, this.y+this.shortDistance*4],
	        stroke: 'black',
	        strokeWidth: 1
	      });
		var lineEighth = new Kinetic.Line({
	        points: [this.x+this.shortDistance*6, this.y+this.shortDistance*6, this.x+this.shortDistance*4, this.y+this.shortDistance*4],
	        stroke: 'black',
	        strokeWidth: 1
	      });
		
		this.layer.add(outRect);
		this.layer.add(middleRect);
		this.layer.add(inRect);
		this.layer.add(lineFirst);
		this.layer.add(lineSecond);
		this.layer.add(lineThird);
		this.layer.add(lineFourth);
		this.layer.add(lineFifth);
		this.layer.add(lineSixth);
		this.layer.add(lineSeventh);
		this.layer.add(lineEighth);
		
		this.stage.add(this.layer);
		
	},
	_drawPlayRocks : function (playStatus) {
		for(var i=0; i < playStatus.playRocks.length ;i++) {
			this._drawPlayRock(playStatus, i);
		}
		
		this.layer.draw();
		
	},
	_drawPlayRock : function (playStatus, number) {
		var self = this;
		
		var playRock = new Kinetic.Circle({
	        x: playStatus.playRocks[number].path.x + this.marginX,
	        y: playStatus.playRocks[number].path.y + this.marginY,
	        radius: this.rockRadius,
	        fill: playStatus.playRocks[number].order
	      });
		
		if ((playStatus.statusType=="CHARM" || playStatus.statusType=="CHARMINMOVE" )&& playStatus.order == this._order && playStatus.playRocks[number].order != this._order) {
			playRock.setOpacity(0.5);
			playRock.setRadius(this.rockRadius);
			playRock.on('click touchstart', function(e) {
				
				this.off("click touchstart");
				this.destroy();
				self.layer.draw();
				self._choiceXRocks(number); 
		      });
		}
		
		if (playStatus.statusType=="MOVE" && playStatus.order == this._order && playStatus.playRocks[number].order == this._order) {
			playRock.on('click touchstart', function(e) {
				self._drawMovePath(number+1);
		      });
		}
		
		this._playRocks.push(playRock);
		this.layer.add(playRock);
		
	},
	_addPlayRock : function (_moveRock) {
		
		var playRock = new Kinetic.Circle({
	        x: _moveRock.getX(),
	        y: _moveRock.getY(),
	        radius: this.rockRadius,
	        fill: _moveRock.getFill()
	      });
		this._playRocks.push(playRock);
		this.layer.add(playRock);
	},
	_drawChoiceMoveRocks : function (playStatus) {
		if (playStatus.statusType=="CHARM") {
			return;
		} 
		
		for(var i=0; i < playStatus.moveRocks.length ;i++) {
			this._drawChoiceMoveRock(playStatus.moveRocks[i], i);
		}
		
		this.layer.draw();
		
	},
	_drawChoiceMoveRock : function (_moveRock, i) {
		var self = this;

		var moveRock = new Kinetic.Circle({
	        x: _moveRock.path.x + self.marginX,
	        y: _moveRock.path.y + self.marginY,
	        radius: this.rockRadius,
	        fill: this._order,
	        opacity: 0.5
	      });
		moveRock.on('click touchstart', function(e) {
			self._addPlayRock(this);
			self._choiceMoveRocks(i);
	      });
		
		this._moveRocks.push(moveRock);
		this.layer.add(moveRock);
	},
	_drawXRocks : function (playStatus) {
		
		for(var i=0; i < playStatus.xrocks.length ;i++) {
			this._drawXRock(playStatus.xrocks[i]);
		}
		
		this.layer.draw();
		
	},
	_drawXRock : function (_xRock) {
		
		var xRock = new Kinetic.Text({
			x: _xRock.path.x + this.marginX -11,
			y: _xRock.path.y + this.marginY -30,
			text: 'x',
			fontSize: 50,
			fontFamily: 'Calibri',
			fill: 'BLACK'
		  });
		this._xRocks.push(xRock);
		this.layer.add(xRock);
		
	},
	_playCheck : function () {
		var self = this;
		var o = new jindo.Timer(); 
		var repeatCurrentCounter=0;
		o.start(function() { 
			var checkUrl = "/gonu/play/api/playCheck.json?chnlNumber=" + self._chnlNumber;
			var ajax = $Ajax(checkUrl, {
				type : 'xhr',
		        method : 'get', 
		        async : false,
		        onload : function(res) {
		        	repeatCurrentCounter--;
		            if(!!res){
						var response = res.json();
						var message = response.message;
						self._playStatus =  response.playStatus;
						if(message == "ok"){
							self._noticeElement.text(response.alarm);
							o.abort();
							self._isClickRock = true;
							self._canvasInit();
							
						} else if (message == "end") {
							self._noticeElement.text(response.alarm);
							o.abort();
							self._isClickRock = true;
							
							for (var i=0; i < self._playRocks.length; i++) {
								self._playRocks[i].off("click touchstart");
							}
							
							$Element("gameOutButton").css('display', 'inline');
							$Element("giveUpButton").css('display', 'none');
							if (response.isPVC) {
								$("charmForm").action = "/gonu/home.gonu";
								
							} else {
								$("charmForm").action = "/gonu/play/chnlSelect.gonu?name="+self._name;
							}
						} else {
							self._noticeElement.text("상대방차례입니다.");
						}	
					} 
		        }
		    });
			
			if(repeatCurrentCounter < 2) {
				ajax.request();
				repeatCurrentCounter++;
			}
			
			return true;
		}, 500);
	},
	_choiceMoveRocks : function (number) {
		var checkUrl = "/gonu/play/api/choiceMoveRock.json?moveRockNumber=" + number + "&chnlNumber=" + this._chnlNumber;
		var self = this;
		
		var ajax = $Ajax(checkUrl, {
			type : 'xhr',
	        method : 'get', 
	        async : false,
	        onload : function(res) {
	            if(!!res){
					var response = res.json();
					var message = response.message;
					if(message == "ok"){
						self._playCheck();
					} else if(message != "ok"){
						location.href = "/gonu/play/view.gonu";
	        		}
				} 
	        }
		});
		ajax.request();
	},
	_choiceXRocks : function (number) {
		var checkUrl = "/gonu/play/api/choiceXRock.json?xRockNumber=" + number + "&chnlNumber=" + this._chnlNumber;
		var self = this;
		var ajax = $Ajax(checkUrl, {
			type : 'xhr',
	        method : 'get', 
	        async : false,
	        onload : function(res) {
	            if(!!res){
					var response = res.json();
					var message = response.message;
					if(message != "ok"){
						self._noticeElement.text("다시 X를 지정해주시기 바랍니다.");
						location.href = "/gonu/play/view.gonu";
	        		}
					self._playCheck();
//					location.href = "/gonu/play/view.gonu";
				} 
	        }
		});
		ajax.request();
	},
	_deletePlayRocks : function () {
		for (var i=0; i < this._playRocks.length; i++) {
			var circle = this._playRocks[i];
			circle.off("click touchstart");
			circle.destroy();
		}
		this._playRocks=[];
		this.layer.draw();
	},
	_deleteChoiceMoveRocks : function () {
		for (var i=0; i < this._moveRocks.length; i++) {
			var moveRock = this._moveRocks[i];
			moveRock.off("click touchstart");
			moveRock.destroy();
		}
		this._moveRocks=[];
		this.layer.draw();
	},
	_deleteXRocks : function () {
		for (var i=0; i < this._xRocks.length; i++) {
			var xRock = this._xRocks[i];
			xRock.destroy();
		}
		this._moveRocks=[];
		this.layer.draw();
	},
	_drawMovePath : function (number) {
		var checkUrl = "/gonu/play/api/movePath.json?rockNumber=" + number + "&chnlNumber=" + this._chnlNumber;
		var self = this;
		self._deleteMoveCircles();
		var ajax = $Ajax(checkUrl, {
			type : 'xhr',
	        method : 'get', 
	        async : false,
	        onload : function(res) {
	            if(!!res){
					var response = res.json();
					var message = response.message;
					if(message == "ok"){
						for(var i=0; i < response.movePath.length; i++){
							
							var moveCircle = new Kinetic.Circle({
						        x: response.movePath[i].x + self.marginX,
						        y: response.movePath[i].y + self.marginY,
						        radius: self.rockRadius,
						        fill: self._order,
						        opacity: 0.5
							});
							
							moveCircle.on('click touchstart', function() {
								var selfCircle = this;
								var anim = new Kinetic.Animation(function(frame) {
									self._playRocks[number-1].setX( selfCircle.getX());
									self._playRocks[number-1].setY(selfCircle.getY());
									}, self.layer);

								anim.start();
								anim.stop();
								
								self._moveRockRequest(number, selfCircle.getX(), selfCircle.getY());
								    
								self._playCheck();
							});
							
							self._moveCircles.push(moveCircle);
							self.layer.add(moveCircle);
						}
						self.layer.draw();
					} else {
						self._deleteMoveCircles();
					    
						self.layer.draw();
					}		
				} 
	        }
		});
		ajax.request();
	},
	_deleteMoveCircles : function () {
		for (var i=0; i < this._moveCircles.length; i++) {
			var circle = this._moveCircles[i];
			circle.off("click touchstart");
			circle.destroy();
		}
		this._moveCircles=[];
		this.layer.draw();
	},
	_moveRockRequest : function (number, x, y) {
		var tempX = x-this.marginX;
		var tempY = y-this.marginY;
		var self = this;
		var moveRockUrl = "/gonu/play/api/moveRock.json?rockNumber="+number+"&chnlNumber="+this._chnlNumber+"&x="+ tempX +"&y="+ tempY;
	    var ajaxMoveRock = $Ajax(moveRockUrl, {
			type : 'xhr',
	        method : 'get', 
	        async : false,
	        onload : function(res) {
	        	if(!!res){
	        		var response = res.json();
	        		var message = response.message;
	        		if(message != "ok") {
	        			self._noticeElement.text("다시 말을 움직여주세요");
	        			location.href = "/gonu/play/view.gonu";
	        		}
	        	}
	        }
	    });
	    ajaxMoveRock.request();
	}
}